package com.elextec.lease.manager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.elextec.framework.common.constants.RunningResult;
import com.elextec.framework.common.constants.WzConstants;
import com.elextec.framework.exceptions.BizException;
import com.elextec.framework.plugins.paging.PageRequest;
import com.elextec.framework.plugins.paging.PageResponse;
import com.elextec.framework.plugins.redis.RedisClient;
import com.elextec.framework.utils.WzStringUtil;
import com.elextec.lease.device.common.DeviceApiConstants;
import com.elextec.lease.manager.request.BizDeviceConfParam;
import com.elextec.lease.manager.service.BizDeviceConfService;
import com.elextec.persist.dao.mybatis.BizBatteryMapperExt;
import com.elextec.persist.dao.mybatis.BizDeviceConfMapperExt;
import com.elextec.persist.dao.mybatis.BizVehicleMapperExt;
import com.elextec.persist.dao.mybatis.SysUserMapperExt;
import com.elextec.persist.field.enums.DeviceType;
import com.elextec.persist.model.mybatis.*;
import com.elextec.persist.model.mybatis.ext.BizDeviceConfExt;
import com.elextec.persist.model.mybatis.ext.BizPowerAndLoction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备参数设置管理Service实现类.
 * Created by wangtao on 2018/1/16.
 */
@Service
public class BizDeviceConfServiceImpl implements BizDeviceConfService {

    @Autowired
    private BizDeviceConfMapperExt bizDeviceConfMapperExt;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private BizBatteryMapperExt bizBatteryMapperExt;

    @Autowired
    private BizVehicleMapperExt bizVehicleMapperExt;

    @Autowired
    private SysUserMapperExt sysUserMapperExt;

    @Override
    public PageResponse<BizDeviceConf> list(boolean needPaging, PageRequest pr) {
        // 查询总记录数
        int devTotal = 0;
        if (null != pr.getTotal() && 0 < pr.getTotal()) {
            devTotal = pr.getTotal();
        } else {
            BizDeviceConfExample devCountExample = new BizDeviceConfExample();
            devCountExample.setDistinct(true);
            devTotal = bizDeviceConfMapperExt.countByExample(devCountExample);
        }
        // 分页查询
        BizDeviceConfExample devLsExample = new BizDeviceConfExample();
        devLsExample.setDistinct(true);
        if (needPaging) {
            devLsExample.setPageBegin(pr.getPageBegin());
            devLsExample.setPageSize(pr.getPageSize());
        }
        List<BizDeviceConf> devLs = bizDeviceConfMapperExt.selectByExample(devLsExample);
        // 组织并返回结果
        PageResponse<BizDeviceConf> presp = new PageResponse<BizDeviceConf>();
        presp.setCurrPage(pr.getCurrPage());
        presp.setPageSize(pr.getPageSize());
        presp.setTotal(devTotal);
        if (null == devLs) {
            presp.setRows(new ArrayList<BizDeviceConf>());
        } else {
            presp.setRows(devLs);
        }
        return presp;
    }

    @Override
    public PageResponse<BizDeviceConf> listByParam(boolean needPaging, BizDeviceConfParam pr) {
        // 查询总记录数
        int devTotal = 0;
        if (null != pr.getTotal() && 0 < pr.getTotal()) {
            devTotal = pr.getTotal();
        } else {
            BizDeviceConfExample devCountExample = new BizDeviceConfExample();
            devCountExample.setDistinct(true);
            BizDeviceConfExample.Criteria devCountCri = devCountExample.createCriteria();
            if (WzStringUtil.isNotBlank(pr.getKeyStr())) {
                devCountCri.andDeviceIdLike("%" + pr.getKeyStr() + "%");
            }
            if (WzStringUtil.isNotBlank(pr.getDeviceType())) {
                devCountCri.andDeviceTypeEqualTo(DeviceType.valueOf(pr.getDeviceType()));
            }
            devTotal = bizDeviceConfMapperExt.countByExample(devCountExample);
        }
        // 分页查询
        BizDeviceConfExample devLsExample = new BizDeviceConfExample();
        devLsExample.setDistinct(true);
        BizDeviceConfExample.Criteria devLsCri = devLsExample.createCriteria();
        if (WzStringUtil.isNotBlank(pr.getKeyStr())) {
            devLsCri.andDeviceIdLike("%" + pr.getKeyStr() + "%");
        }
        if (WzStringUtil.isNotBlank(pr.getDeviceType())) {
            devLsCri.andDeviceTypeEqualTo(DeviceType.valueOf(pr.getDeviceType()));
        }
        if (needPaging) {
            devLsExample.setPageBegin(pr.getPageBegin());
            devLsExample.setPageSize(pr.getPageSize());
        }
        List<BizDeviceConf> devLs = bizDeviceConfMapperExt.selectByExample(devLsExample);
        // 组织并返回结果
        PageResponse<BizDeviceConf> presp = new PageResponse<BizDeviceConf>();
        presp.setCurrPage(pr.getCurrPage());
        presp.setPageSize(pr.getPageSize());
        presp.setTotal(devTotal);
        if (null == devLs) {
            presp.setRows(new ArrayList<BizDeviceConf>());
        } else {
            presp.setRows(devLs);
        }
        return presp;
    }

    @Override
    public PageResponse<BizDeviceConfExt> listByParamWithPowerAndLocation(boolean needPaging, BizDeviceConfParam pr) {
        // 查询总记录数
        int devTotal = 0;
        if (null != pr.getTotal() && 0 < pr.getTotal()) {
            devTotal = pr.getTotal();
        } else {
            BizDeviceConfExample devCountExample = new BizDeviceConfExample();
            devCountExample.setDistinct(true);
            BizDeviceConfExample.Criteria devCountCri = devCountExample.createCriteria();
            if (WzStringUtil.isNotBlank(pr.getKeyStr())) {
                devCountCri.andDeviceIdLike("%" + pr.getKeyStr() + "%");
            }
            if (WzStringUtil.isNotBlank(pr.getDeviceType())) {
                devCountCri.andDeviceTypeEqualTo(DeviceType.valueOf(pr.getDeviceType()));
            }
            devTotal = bizDeviceConfMapperExt.countByExample(devCountExample);
        }
        // 分页查询
        BizDeviceConfExample devLsExample = new BizDeviceConfExample();
        devLsExample.setDistinct(true);
        BizDeviceConfExample.Criteria devLsCri = devLsExample.createCriteria();
        if (WzStringUtil.isNotBlank(pr.getKeyStr())) {
            devLsCri.andDeviceIdLike("%" + pr.getKeyStr() + "%");
        }
        if (WzStringUtil.isNotBlank(pr.getDeviceType())) {
            devLsCri.andDeviceTypeEqualTo(DeviceType.valueOf(pr.getDeviceType()));
        }
        if (needPaging) {
            devLsExample.setPageBegin(pr.getPageBegin());
            devLsExample.setPageSize(pr.getPageSize());
        }
        List<BizDeviceConf> devLs = bizDeviceConfMapperExt.selectByExample(devLsExample);
        List<BizDeviceConfExt> devExtLs = new ArrayList<BizDeviceConfExt>();
        BizDeviceConfExt devExtVo = null;
        BizDeviceConfKey searchKey = null;
        BizPowerAndLoction plVo = null;
        for (BizDeviceConf devVo : devLs) {
            devExtVo = new BizDeviceConfExt();
            devExtVo.setDeviceId(devVo.getDeviceId());
            devExtVo.setDeviceType(devVo.getDeviceType());
            devExtVo.setPerSet(devVo.getPerSet());
            devExtVo.setRequest(devVo.getRequest());
            devExtVo.setReset(devVo.getReset());
            searchKey = new BizDeviceConfKey();
            searchKey.setDeviceId(devVo.getDeviceId());
            searchKey.setDeviceType(devVo.getDeviceType());
            plVo = getPowerAndLocationByDeviceId(searchKey);
            devExtVo.setLat(plVo.getLat());
            devExtVo.setLon(plVo.getLon());
            devExtVo.setRsoc(plVo.getRsoc());
            devExtLs.add(devExtVo);
        }
        // 组织并返回结果
        PageResponse<BizDeviceConfExt> presp = new PageResponse<BizDeviceConfExt>();
        presp.setCurrPage(pr.getCurrPage());
        presp.setPageSize(pr.getPageSize());
        presp.setTotal(devTotal);
        if (null == devExtLs) {
            presp.setRows(new ArrayList<BizDeviceConfExt>());
        } else {
            presp.setRows(devExtLs);
        }
        return presp;
    }

    @Override
    public void insertBizDeviceConfs(List<BizDeviceConf> deviceConfs) {
        int i = 0;
        BizDeviceConf insertVo = null;
        try {
            for (; i < deviceConfs.size(); i++) {
                insertVo = deviceConfs.get(i);
                bizDeviceConfMapperExt.insertSelective(insertVo);
            }
        } catch (Exception ex) {
            throw new BizException(RunningResult.DB_ERROR.code(), "第" + i + "条记录插入时发生错误", ex);
        }
    }

    @Override
    public void insertBizDeviceConf(BizDeviceConf deviceConf) {
        // 设备重复提示错误
        BizDeviceConfExample devExample = new BizDeviceConfExample();
        BizDeviceConfExample.Criteria devCriteria = devExample.createCriteria();
        devCriteria.andDeviceIdEqualTo(deviceConf.getDeviceId());
        devCriteria.andDeviceTypeEqualTo(deviceConf.getDeviceType());
        int devCnt = bizDeviceConfMapperExt.countByExample(devExample);
        if (0 < devCnt) {
            throw new BizException(RunningResult.MULTIPLE_RECORD.code(), "该设备已存在");
        }
        // 保存用户信息
        try {
            bizDeviceConfMapperExt.insertSelective(deviceConf);
        } catch (Exception ex) {
            throw new BizException(RunningResult.DB_ERROR.code(), "记录插入时发生错误", ex);
        }
    }

    @Override
    public void updateBizDeviceConf(BizDeviceConf deviceConf) {
        bizDeviceConfMapperExt.updateByPrimaryKeySelective(deviceConf);
    }

    @Override
    public void deleteBizDeviceConfs(List<BizDeviceConfKey> deviceConfKeys) {
        int i = 0;
        try {
            for (; i < deviceConfKeys.size(); i++) {
                bizDeviceConfMapperExt.deleteByPrimaryKey(deviceConfKeys.get(i));
            }
        } catch (Exception ex) {
            throw new BizException(RunningResult.DB_ERROR.code(), "第" + i + "条记录删除时发生错误", ex);
        }
    }

    @Override
    public BizDeviceConf getBizDeviceConfByPrimaryKey(BizDeviceConfKey key) {
        return bizDeviceConfMapperExt.selectByPrimaryKey(key);
    }

    @Override
    public BizPowerAndLoction getPowerAndLocationByDeviceId(BizDeviceConfKey dck) {

        // 获得定位
        JSONObject locObj = (JSONObject) redisClient.hashOperations().get(WzConstants.GK_DEVICE_LOC_MAP,dck.getDeviceId() + WzConstants.KEY_SPLIT + dck.getDeviceType().toString());
        Double lonVal = 0.0;
        Double latVal = 0.0;
        try {
            lonVal = locObj.getDoubleValue(DeviceApiConstants.REQ_LON);
            latVal = locObj.getDoubleValue(DeviceApiConstants.REQ_LAT);
        } catch (Exception e) {
            lonVal = 0.0;
            latVal = 0.0;
        }

        JSONObject powerObj =  (JSONObject) redisClient.hashOperations().get(WzConstants.GK_DEVIE_POWER_MAP, dck.getDeviceId() + WzConstants.KEY_SPLIT + dck.getDeviceType().toString());
        String powerVal = null;
        try {
            powerVal = powerObj.getString(DeviceApiConstants.REQ_RSOC);
        } catch (Exception e) {
            powerVal = "--";
        }
        BizPowerAndLoction pal = new BizPowerAndLoction();
        pal.setLat(latVal);
        pal.setLon(lonVal);
        pal.setRsoc(powerVal);
        return pal;
    }

    @Override
    public Map<String, Object> getRelationInformationByDevice(String deviceId) {
        Map<String,Object> map = new HashMap<String, Object>(); // 返回结果
        BizDeviceConfExample bizDeviceConfExample = new BizDeviceConfExample();
        BizDeviceConfExample.Criteria criteria = bizDeviceConfExample.createCriteria();
        criteria.andDeviceIdEqualTo(deviceId);
        criteria.andDeviceTypeEqualTo(DeviceType.BATTERY);
        // 确定设备是否存在
        int cnt = bizDeviceConfMapperExt.countByExample(bizDeviceConfExample);
        if (1 == cnt) {
            // 查电池信息
            BizBattery bizBattery = bizBatteryMapperExt.getBizBatteryInfoByDevice(deviceId);//根据设备id获取电池信息
            if (null == bizBattery || WzStringUtil.isBlank(bizBattery.getId())) {
                bizBattery = new BizBattery();
                bizBattery.setId("");
                bizBattery.setMfrsId("");
                bizBattery.setBatteryParameters("");
                bizBattery.setBatteryPn("");
                bizBattery.setBatteryName("");
                bizBattery.setCreateTime(null);
                bizBattery.setBatteryBrand("");
                bizBattery.setBatteryCode("");
                bizBattery.setBatteryStatus(null);
                bizBattery.setCreateUser("");
                bizBattery.setUpdateTime(null);
                bizBattery.setUpdateUser("");
            } else {
                if (WzStringUtil.isBlank(bizBattery.getBatteryName())) {
                    bizBattery.setBatteryName("");
                }
                if (WzStringUtil.isBlank(bizBattery.getBatteryBrand())) {
                    bizBattery.setBatteryName("");
                }
                if (WzStringUtil.isBlank(bizBattery.getBatteryPn())) {
                    bizBattery.setBatteryPn("");
                }
                if (WzStringUtil.isBlank(bizBattery.getBatteryParameters())) {
                    bizBattery.setBatteryParameters("");
                }
                if (WzStringUtil.isBlank(bizBattery.getMfrsId())) {
                    bizBattery.setMfrsId("");
                }
            }
            map.put(WzConstants.KEY_BATTERY_INFO, bizBattery);
            // 查车辆信息
            BizVehicle bizVehicle = null;
            if (WzStringUtil.isNotBlank(bizBattery.getId())) {
                bizVehicle = bizVehicleMapperExt.getBizVehicleInfoByBattery(bizBattery.getId());
            }
            if (null == bizVehicle || WzStringUtil.isBlank(bizBattery.getId())) {
                bizVehicle = new BizVehicle();
                bizVehicle.setMfrsId("");
                bizVehicle.setVehicleMadeIn("");
                bizVehicle.setVehicleBrand("");
                bizVehicle.setVehiclePn("");
                bizVehicle.setCreateTime(null);
                bizVehicle.setId("");
                bizVehicle.setUpdateTime(null);
                bizVehicle.setCreateUser("");
                bizVehicle.setUpdateUser("");
                bizVehicle.setVehicleCode("");
                bizVehicle.setVehicleStatus(null);
            } else {
                if (WzStringUtil.isBlank(bizVehicle.getVehiclePn())) {
                    bizVehicle.setVehiclePn("");
                }
                if (WzStringUtil.isBlank(bizVehicle.getVehicleBrand())) {
                    bizVehicle.setVehicleBrand("");
                }
                if (WzStringUtil.isBlank(bizVehicle.getVehicleMadeIn())) {
                    bizVehicle.setVehicleMadeIn("");
                }
                if (WzStringUtil.isBlank(bizVehicle.getMfrsId())) {
                    bizVehicle.setMfrsId("");
                }
            }
            map.put(WzConstants.KEY_VEHICLE_INFO, bizVehicle);
            // 查询用户
            SysUser sysUser = null;
            if (WzStringUtil.isNotBlank(bizVehicle.getId())) {
                sysUser = sysUserMapperExt.getUserByVehicle(bizVehicle.getId());
            }
            if (null == sysUser || WzStringUtil.isBlank(sysUser.getId())) {
                sysUser = new SysUser();
                sysUser.setId("");
                sysUser.setLoginName("");
                sysUser.setUserMobile("");
                sysUser.setNickName("");
                sysUser.setUserName("");
                sysUser.setUserPid("");
            } else {
                if (WzStringUtil.isBlank(sysUser.getUserIcon())) {
                    sysUser.setUserIcon("");
                }
                if (WzStringUtil.isBlank(sysUser.getNickName())) {
                    sysUser.setNickName("");
                }
                if (WzStringUtil.isBlank(sysUser.getUserName())) {
                    sysUser.setUserName("");
                }
                if (WzStringUtil.isBlank(sysUser.getUserPid())) {
                    sysUser.setUserPid("");
                }
                if (WzStringUtil.isBlank(sysUser.getUserIcFront())) {
                    sysUser.setUserIcFront("");
                }
                if (WzStringUtil.isBlank(sysUser.getUserIcBack())) {
                    sysUser.setUserIcBack("");
                }
                if (WzStringUtil.isBlank(sysUser.getUserIcGroup())) {
                    sysUser.setUserIcGroup("");
                }
                if (WzStringUtil.isBlank(sysUser.getOrgId())) {
                    sysUser.setOrgId("");
                }
                if (WzStringUtil.isBlank(sysUser.getCreateUser())) {
                    sysUser.setCreateUser("");
                }
                if (WzStringUtil.isBlank(sysUser.getUpdateUser())) {
                    sysUser.setUpdateUser("");
                }
            }
            map.put(WzConstants.KEY_USER_INFO, sysUser);
        } else {
            throw new BizException(RunningResult.PARAM_VERIFY_ERROR.code(), "设备(数量：" + cnt +  ")不存在或数量异常");
        }
        return map;
    }
}
